package bluetooth;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import java.util.Vector;
import javax.bluetooth.RemoteDevice;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import components.IntroCanvas;
import midlet.ClientApp;



/**
 * 初始界面
 * @author cccssw
 * 
 */
public class DeviceListCanvas extends List implements CommandListener {
    //蓝牙服务类

    private BlueDeviceSearcher blueDevice = null;
    //按钮控件
    private Command cmdConnect = null;
    private Command cmdRefresh = null;
    private Command cmdExit = null;
    private Command cmdBack = null;
    private MIDlet instance = null;
    
    private Vector urls = new Vector();
    private final String ID_TARGET_NAME = "targetNames";
    private final String ID_TARGET_URL = "targetUrls";

    private BlueComm blueConnection=null;
    
    public DeviceListCanvas(MIDlet instance) {
        super("d", List.IMPLICIT);
        this.setTitle("Connect to PC");
        this.instance=instance;
        InitList();
    }

    public synchronized BlueComm getBlueConnection(){
        if(blueConnection==null){
            try {
                wait();
            } catch (InterruptedException ex) {
            }
        }
        
        return blueConnection;
    }
    
    private void saveRecord(String key, String str) {
        try {
            RecordStore rs = RecordStore.openRecordStore(key, true);
            byte strbyte[] = str.getBytes();
            rs.addRecord(strbyte, 0, strbyte.length);
            rs.closeRecordStore();
        } catch (RecordStoreException ex) {
        }
    }

    private void saveTarget(String name, String url) {
        //save only one record!
        System.out.println("saving " + name + " at " + url);
        try {
            RecordStore.deleteRecordStore(this.ID_TARGET_NAME);
            RecordStore.deleteRecordStore(this.ID_TARGET_URL);
                    } catch (RecordStoreException ex) {
        }
        saveRecord(this.ID_TARGET_NAME,name);
        saveRecord(this.ID_TARGET_URL,url);
        
    }

    private void LoadTarget() {
        try {
            RecordStore rs = RecordStore.openRecordStore(this.ID_TARGET_NAME, false);
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            while (re.hasNextElement()) {
                byte rec[] = re.nextRecord();
                String str = new String(rec, 0, rec.length);
                //name appends to list
                this.append(str, null);
            }
            re.destroy();
            rs.closeRecordStore();

            RecordStore rs2 = RecordStore.openRecordStore(this.ID_TARGET_URL, false);
            RecordEnumeration re2 = rs2.enumerateRecords(null, null, false);
            while (re2.hasNextElement()) {
                byte rec[] = re2.nextRecord();
                String str = new String(rec, 0, rec.length);
                //add to Vector
                urls.addElement(str);
            }
            re2.destroy();
            rs2.closeRecordStore();

        } catch (RecordStoreException ex) {
        }
    }

    private synchronized void command_Connect() {
        if (blueDevice != null) {
            //connect by object
            Vector devices = blueDevice.getDevices();
            BlueComm bc = new BlueComm((RemoteDevice) devices.elementAt(this.getSelectedIndex()));

            if (bc.Connect()) {
                saveTarget(bc.getDeviceName(), bc.getUrl());

                blueConnection=bc;
                notify();

            }
        } else {
            //connect by url
            BlueComm bc = new BlueComm((String) urls.elementAt(this.getSelectedIndex()));

            if (bc.Connect()) {
                blueConnection=bc;
                notify();
            }
        }

    }

    public void commandAction(Command cmd, Displayable dis) {
        if (cmd == cmdConnect) {
            command_Connect();
        } else if (cmd == cmdRefresh) {
            this.deleteAll();
           
            blueDevice = new BlueDeviceSearcher(this);
            new Thread(blueDevice).start();
        }else if(cmd==cmdExit){
            ClientApp.exitMidlet();
        }else if(cmd==cmdBack){
            Display.getDisplay(instance).setCurrent(new IntroCanvas());
        }
    }

    private void InitList() {
        System.out.println("init list");

        cmdConnect = new Command("Connect", Command.OK, 1);
        this.addCommand(cmdConnect);

        cmdRefresh = new Command("Update", Command.SCREEN, 1);
        this.addCommand(cmdRefresh);

        cmdExit = new Command("Exit", Command.SCREEN, 1);
        this.addCommand(cmdExit);
        
        cmdBack = new Command("Back",Command.BACK,1);
        this.addCommand(cmdBack);
        
        this.setCommandListener(this);

        //load file or some
        this.deleteAll();
        LoadTarget();
     

    }

}
